<template>
  <div class="test">
    <div class="product-item">
      <div class="product-img">        
        <img :src="productInfo.original_img"  @click.stop="goDetail" alt class="product-proview-img" />
      </div>
      <div class="tag">
        <span class="product-tag" v-if="productInfo.prom_name">{{productInfo.prom_name}}</span>
      </div>
      <h5 class="goods_name">{{productInfo.goods_name}}</h5>      
      <p class="product-introduce">{{productInfo.goods_remark}}</p>
      <div class="product-info">
        <div class="product-price" @click.stop="goDetail">
          <span class="price">{{productInfo.shop_price}}</span>
          <span class="weight">/{{productInfo.weight}}g</span>
        </div>
        <div class="product-add">
          <img src="/img/30.png" @click="addCart" alt class="product-add-img" v-if="productInfo.cart_info.goods_num==0"/>
          <van-stepper v-model="productInfo.cart_info.goods_num" v-else min="0" max="10" @change="updateCartNum"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Stepper } from 'vant';
Vue.use(Stepper);
export default {
  props: {
    productInfo: {
      type: Object,
      default: () => {return {}},
    },
    value:{
      type: [Number, String],
      default: 0
    },
    isOldVip: {
      type: Boolean,
      default: false
    }
  },
  data(){
    return {
      doNotUpdate: false
    }
  },
  mounted(){
    if(this.isOldVip) {
      this.productInfo.cart_info = Object.assign( this.productInfo.cart_info || {},{
        goods_num: this.value
      })
    }
  },
  methods:{
    goDetail(){
      this.$router.push({
        path: '/product_detail',
        query: {
          id: this.productInfo.goods_id,
          from: this.$route.name
        }
      })
    },
    addCart(){
      if(this.isOldVip) {
        this.productInfo.cart_info.goods_num = 1
        return false
      }
      this.$store.dispatch('add2Cart',{
        goods_id: this.productInfo.goods_id
      }).then( res =>{
        this.productInfo.cart_info.goods_num = 1
        this.productInfo.cart_info.id = res.data.result.cart_id
      }).catch(e=>{

      })
    },
    updateCartNum(value = 0){
      if(this.isOldVip) {
        this.productInfo.cart_info.goods_num = value
        return false
      }
      if(this.doNotUpdate) return false
      this.$store.dispatch('updateCartNum',{
        id: this.productInfo.cart_info.id,
        num: value
      }).then( res =>{
        this.productInfo.cart_info.goods_num = value
      }).catch(e=>{
        // this.doNotUpdate = true
        // this.productInfo.cart_info.goods_num = beforeNum || 0
      })
    }
  },
  watch:{
    'productInfo.cart_info.goods_num'(v){
      this.$emit('input', v)
    }
  }
};
</script>

<style lang='less'>
@import "./porduct-item.less";
</style>
